#!/usr/bin/env bash

set -e

# CLI handling.
arch='x86_64'
debug=false
debug_qemu=''
kgdb=false
nographic=false
extra_append=''
extra_flags=''
while getopts a:de:knq OPT; do
  case "$OPT" in
    a)
      arch="$OPTARG"
      ;;
    d)
      debug=true
      extra_flags="$extra_flags -S -s"
      ;;
    e)
      extra_append="$extra_append $OPTARG"
      ;;
    k)
      debug=true
      extra_append="$extra_append kgdbwait"
      # For those who want to try KDB.
      #extra_append="$extra_append kgdbwait kgdboc=kbd"
      extra_flags="$extra_flags -serial tcp::1234,server,nowait"
      kgdb=true
      ;;
    n)
      extra_append="$extra_append console=ttyS0"
      extra_flags="$extra_flags -nographic"
      nographic=true
      ;;
    q)
      debug_qemu='gdb -q -ex start --args'
      ;;
  esac
done
shift "$(($OPTIND - 1))"
extra_flags="$extra_flags $@"

buildroot_out_dir="./buildroot/output.${arch}~"
images_dir="$buildroot_out_dir/images"
qemu_common="\
$debug_qemu \
$buildroot_out_dir/host/usr/bin/qemu-system-${arch} \
-m 128M \
-monitor telnet::45454,server,nowait \
-net user \
-smp 1 \
"
# The base QEMU commands are found under board/qemu/*/readme.tx
case "$arch" in
  'x86_64')
    if $kgdb; then
      extra_append="$extra_append kgdboc=ttyS0,115200"
    fi
    cmd="$qemu_common \
      -M pc \
      -append 'root=/dev/vda $extra_append' \
      -device edu \
      -drive file=${images_dir}/rootfs.ext2,if=virtio,format=raw \
      -kernel ${images_dir}/bzImage \
      -net nic,model=virtio \
      $extra_flags
    "
  ;;
  'arm')
    if $kgdb; then
      extra_append="$extra_append kgdboc=ttyAMA0,115200"
    fi
    cmd="$qemu_common \
      -M versatilepb \
      -append 'root=/dev/sda $extra_append' \
      -drive file=${images_dir}/rootfs.ext2,if=scsi,format=raw \
      -dtb ${images_dir}/versatile-pb.dtb \
      -kernel ${images_dir}/zImage \
      -net nic,model=rtl8139 \
      -serial stdio \
      $extra_flags
    "
  ;;
  'mips64')
    cmd="$qemu_common \
      -M malta \
      -append 'root=/dev/hda $extra_append' \
      -cpu I6400 \
      -drive file=${images_dir}/rootfs.ext2,format=raw \
      -kernel ${images_dir}/vmlinux \
      -nographic \
      -net nic,model=pcnet \
      $extra_flags
    "
  ;;
esac
eval "$cmd"
